import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
const useShopStore = defineStore(
  'shop',
  () => {
    const shopCarList = ref([]);
    const token = ref('');
    const refreshToken = ref('');
    const userInfo = ref({});
    const address = ref({});

    // 总数量
    const totalNum = computed(() => {
      return shopCarList.value.reduce((result, item) => {
        return (result += item?.number);
      }, 0);
    });

    // 选中的总数量

    const totalSelectedNum = computed(() => {
      return shopCarList.value.reduce((result, item) => {
        if (item?.isSelected) {
          result += item?.number;
        }
        return result;
      }, 0);
    });
    //  选中的总价格
    const totalPrice = computed(() => {
      return shopCarList.value.reduce((result, item) => {
        if (item?.isSelected) {
          result += parseInt(item?.number) * parseInt(item?.price);
        }
        return result;
      }, 0);
    });

    const addShopCarList = (goodsdetail) => {
      let index = shopCarList.value.findIndex(
        (item) => item.id === goodsdetail.id
      );
      if (index > -1) {
        shopCarList.value[index].number += goodsdetail.number;
      } else {
        shopCarList.value.push(goodsdetail);
      }
    };

    const setShopCarList = (ShopCarList) => {
      shopCarList.value = ShopCarList;
    };

    const setToken = (Token) => {
      token.value = Token;
    };

    const setRefreshToken = (RefreshToken) => {
      refreshToken.value = RefreshToken;
    };

    const setUserInfo = (UserInfo) => {
      userInfo.value = UserInfo;
    };

    const setAvatar = (Avatar) => {
      userInfo.value.avatar = Avatar;
    };

    const setAddress = (Address) => {
      address.value = Address;
    };

    return {
      shopCarList,
      token,
      refreshToken,
      userInfo,
      address,
      totalNum,
      totalSelectedNum,
      totalPrice,
      addShopCarList,
      setShopCarList,
      setToken,
      setRefreshToken,
      setUserInfo,
      setAvatar,
      setAddress,
    };
  },
  {
    persist: true,
  }
);

export default useShopStore;
